package com.jzo2o.foundations.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 服务表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2024-07-20
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Resource
    private ServeItemMapper serveItemMapper;

    @Resource
    private RegionMapper regionMapper;

    /**
     * 区域服务分页查询
     *
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
    }

    /**
     * 批量添加区域服务
     *
     * @param serveUpsertReqDTOList
     */
    @Override
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        //遍历serveUpsertReqDTOList
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList) {
            //合法性校验,serve_item是否启用，如果未启用不能添加
            Long serveItemId = serveUpsertReqDTO.getServeItemId();
            ServeItem serveItem = serveItemMapper.selectById(serveItemId);
            if (ObjectUtils.isNull(serveItem) || serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
                //抛出异常
                throw new ForbiddenOperationException("服务项不存在或服务项未启动不允许添加");
            }
            //同一个区域下不能添加相同的服务
            //sql: select count(*) from serve where serve_item_id=? and region_id=?
            Integer count = lambdaQuery() //相当于new LambdaUpdateWrapper<Serve>()
                    .eq(Serve::getServeItemId, serveUpsertReqDTO.getServeItemId())
                    .eq(Serve::getRegionId, serveUpsertReqDTO.getRegionId())
                    .count();
            if (count > 0) {
                throw new ForbiddenOperationException(serveItem.getName() + "服务项已存在");

            }
            //组装数据
            Serve serve = BeanUtils.toBean(serveUpsertReqDTO, Serve.class);
            Long regionId = serve.getRegionId();
            Region region = regionMapper.selectById(regionId);
            String cityCode = region.getCityCode();
            serve.setCityCode(cityCode);
            //向serve插入数据
            baseMapper.insert(serve);
        }
    }

    /**
     * 删除指定id的区域服务
     * @param id 区域服务id
     */
    @Override
    public void delete(Long id) {
        //先根据id查询库中是否有这条记录
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtils.isNull(serve)) {
            throw new ForbiddenOperationException("区域服务信息不存在");
        }
        //查看服务记录是否是草稿状态和下架状态，只有这俩个状态才能删除
        if(serve.getSaleStatus() != FoundationStatusEnum.INIT.getStatus() || serve.getSaleStatus() != FoundationStatusEnum.DISABLE.getStatus()){
            throw new ForbiddenOperationException("服务记录不是下架状态和草稿状态无法删除");
        }
        //进行删除
        int row = baseMapper.deleteById(id);
        if(row == 0){
            throw new CommonException("删除区域服务记录失败");
        }
    }

    /**
     * 修改区域服务
     *
     * @param id    区域服务id主键
     * @param price 区域服务价格
     */
    @Override
    public Serve update(Long id, BigDecimal price) {
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if (!update) {
            throw new CommonException("修改服务价格失败");
        }
        Serve serve = baseMapper.selectById(id);
        return serve;
    }

    /**
     * 区域服务上架
     *
     * @param id 区域服务id
     */
    @Override
    public Serve onSale(Long id) {
        //根据id查询serve信息
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtils.isNull(serve)) {
            throw new ForbiddenOperationException("区域服务信息不存在");
        }
        //如果serve的sale_status是0或1可以上架
        Integer saleStatus = serve.getSaleStatus(); //售卖状态
        if (!(saleStatus == FoundationStatusEnum.INIT.getStatus() || saleStatus == FoundationStatusEnum.OFFSALE.getStatus())) {
            throw new ForbiddenOperationException("区域服务的状态是草稿或下架时方可上架");
        }
        //如果服务项没有启用不能上架
        Long serveItemId = serve.getServeItemId(); //服务项id
        ServeItem serveItem = serveItemMapper.selectById(serveItemId);//服务项信息
        Integer activeStatus = serveItem.getActiveStatus(); //状态
        if (activeStatus != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务项的状态未启用不能上架");
        }

        //更新sale_status
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ONSALE.getStatus())
                .update();
        if(!update){
            throw new CommonException("服务上架失败");
        }
        return baseMapper.selectById(id);
    }

    /**
     * 区域服务下架
     * @param id 区域服务id
     */
    @Override
    public void offSale(Long id) {
        //1.根据id查询区域服务
        Serve serve = baseMapper.selectById(id);
        //判断是否为空
        if (ObjectUtils.isNull(serve)) {
            throw new CommonException("此区域服务不存在");
        }
        //只有状态是上架才能下架
        if(serve.getSaleStatus() != FoundationStatusEnum.ONSALE.getStatus()){
            throw new CommonException("服务没有上架，不能下架");
        }
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.OFFSALE.getStatus())
                .update();
        if(!update){
            throw new CommonException("服务下架失败");
        }
    }

    /**
     * 区域服务设置热门
     * @param id 区域服务id
     */
    @Override
    public void onHot(Long id) {
        //根据区域服务id获得数据
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtils.isNull(serve)) {
            throw new CommonException("该区域服务未找到");
        }
        //只有是非热门状态下才能设置为热门
        if(serve.getIsHot() != FoundationStatusEnum.OFFHOT.getStatus()){
            throw new CommonException("此服务项是热门状态没法设置为非热门");
        }

        //只有此服务项在启用状态下，才能设置为热门
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        Integer activeStatus = serveItem.getActiveStatus();
        if(activeStatus != FoundationStatusEnum.ENABLE.getStatus()){
            throw new CommonException("该服务未请用，不能设置热门状态");
        }

        // 更新状态
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getIsHot, FoundationStatusEnum.ONHOT.getStatus())
                .update();
        if(!update){
            throw new CommonException("设置热门状态失败");
        }
    }
    /**
     * 区域服务设置为 非热门
     * @param id 区域服务id
     */
    @Override
    public void offHot(Long id) {
        //根据区域服务id查找对应的数据
        Serve serve = baseMapper.selectById(id);
        //判断是否存在此数据
        if (ObjectUtils.isNull(serve)) {
            throw new CommonException("此区域服务不存在");
        }
        //只有是热门状态才能转成非热门
        if(serve.getIsHot() != FoundationStatusEnum.ONHOT.getStatus()){
            throw new CommonException("此服务是非热门状态，无法设置");
        }
        //查询该服务项是否是启用状态
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        Integer activeStatus = serveItem.getActiveStatus();
        if(activeStatus != FoundationStatusEnum.ENABLE.getStatus()){
            throw new CommonException("该服务项未启用，不能进行设置非热门状态");
        }
        //将状态更新非热门
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getIsHot, FoundationStatusEnum.OFFHOT.getStatus())
                .update();
        if(!update){
            throw new CommonException("设置为非热门状态失败");
        }
    }
}
